import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;

import messagepasser.DocInfo;
import messagepasser.DocPermissions;
import messagepasser.Document;
import messagepasser.UserInfo;
import messagepasser.ListenSocket;


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * LoggedIn.java
 *
 * Created on Mar 17, 2010, 8:52:59 PM
 */

/**
 *
 * @author keerthy
 */
public class LoggedIn extends javax.swing.JFrame {

	UserInfo[] users;
	List<DocInfo> docs;
	List<Document> userDocs = new ArrayList <Document>();
	ListenSocket listeningServer;
	Vector<String> userNames = new Vector<String>();
	Vector<String> docNames = new Vector<String>();
	UserInfo me;
	Server tecBoxServer;
	TextChat txtchat;
	Document chatDoc;
	DocPermissions docPerm;
	Thread t=new Thread();
	UserInfo destUser=null;

	String destForTextChat;
	String destForVoiceChat;

	public javax.swing.JList getOnlineUsers() {
		return onlineUsers;
	}

	public void setOnlineUsers(javax.swing.JList onlineUsers) {
		this.onlineUsers = onlineUsers;
	}

	/** Creates new form LoggedIn */
	public LoggedIn() {
		//initComponents();
	}

	public LoggedIn(UserInfo user, Server s){
		me = user;
		tecBoxServer = s;

		initComponents();

		try {
			Client myself = new Client_Servant(this, user.getUserid());
			s.register(myself, user.getUserid());
		} catch (RemoteException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		try {
			docs = s.getDocuments(user.getUserid());
			for (DocInfo d : docs) {
				docNames.add(d.getDocname());
			}
			docList.setListData(docNames);

			listeningServer = new ListenSocket (user.getPort(), userDocs);
			listeningServer.start();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {
			users = s.getonlineUsers(user.getUserid());


			for (UserInfo u : users) {
				//  System.out.println(u.getUsername());
				if (u.isOnlinestatus()) {
					userNames.add(u.getUsername());
				}

			}
			onlineUsers.setListData(userNames);
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		for (DocInfo d : docs) {
			System.out.println(d.getDocname());
			DocPermissions[] perDocusers;
			try {
				perDocusers = s.getDocUsers(d.getDocid());
				userDocs.add(new Document(d.getDocid(), user, users, perDocusers, d.getDocname()));
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}  
		this.setTitle(me.getUsername());

		//start thread for evrry user
		txtchat=new TextChat(me,users,this);
		initPanes (userDocs);  


	}

	public void initPanes(List <Document> userDocs) {

		for (Document d : userDocs) {
			createPage (d);
			this.jTabbedPane1.addTab( d.getDocName(), d.panel );
		}
	}

	public void createPage(Document d)
	{
		d.panel = new JPanel();
		d.contentBox = new JTextArea(d.getContent());
		//content.setBounds( 10, 15, 150, 20 );

		d.panel.add( d.contentBox );
	}


	/** This method is called from within the constructor to
	 * initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
	// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
	private void initComponents() {

		jSeparator1 = new javax.swing.JSeparator();
		jPanel1 = new javax.swing.JPanel();
		jScrollPane1 = new javax.swing.JScrollPane();
		docList = new javax.swing.JList();
		jLabel1 = new javax.swing.JLabel();
		jScrollPane2 = new javax.swing.JScrollPane();
		onlineUsers = new javax.swing.JList();
		jLabel2 = new javax.swing.JLabel();
		jPanel3 = new javax.swing.JPanel();
		jScrollPane3 = new javax.swing.JScrollPane();
		jTextArea1 = new javax.swing.JTextArea();
		jTextField1 = new javax.swing.JTextField();
		jTabbedPane1 = new javax.swing.JTabbedPane();
		jPanel2 = new javax.swing.JPanel();
		jScrollPane4 = new javax.swing.JScrollPane();
		jTextArea2 = new javax.swing.JTextArea();
		jMenuBar1 = new javax.swing.JMenuBar();
		jMenu1 = new javax.swing.JMenuItem();
		jMenu2 = new javax.swing.JMenuItem();
		jMenu3 = new javax.swing.JMenuItem();
		jMenu4 = new javax.swing.JMenuItem();
		jMenu5 = new javax.swing.JMenuItem();
		jMenu6 = new javax.swing.JMenuItem();

		setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

		jPanel1.setBackground(new java.awt.Color(153, 153, 255));

		docList.setModel(new javax.swing.AbstractListModel() {
			String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
			public int getSize() { return strings.length; }
			public Object getElementAt(int i) { return strings[i]; }
		});
		jScrollPane1.setViewportView(docList);

		jLabel1.setText("Documents");

		onlineUsers.setModel(new javax.swing.AbstractListModel() {
			String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
			public int getSize() { return strings.length; }
			public Object getElementAt(int i) { return strings[i]; }
		});

		onlineUsers.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				onlineUsersMouseClicked(evt);
			}
		});
		jScrollPane2.setViewportView(onlineUsers);

		jLabel2.setText("Users");

		javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
		jPanel1.setLayout(jPanel1Layout);
		jPanel1Layout.setHorizontalGroup(
				jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(jPanel1Layout.createSequentialGroup()
						.addGap(75, 75, 75)
						.addComponent(jLabel2)
						.addContainerGap(93, Short.MAX_VALUE))
						.addGroup(jPanel1Layout.createSequentialGroup()
								.addGap(63, 63, 63)
								.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
								.addContainerGap(66, Short.MAX_VALUE))
								.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 195, Short.MAX_VALUE)
								.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 195, Short.MAX_VALUE)
		);
		jPanel1Layout.setVerticalGroup(
				jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(jPanel1Layout.createSequentialGroup()
						.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 215, Short.MAX_VALUE)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE))
		);

		jPanel3.setBackground(new java.awt.Color(255, 255, 255));

		jTextArea1.setColumns(20);
		jTextArea1.setRows(5);
		jTextArea1.setText("Chat window");
		jScrollPane3.setViewportView(jTextArea1);

		jTextField1.setText("");
		jTextField1.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jTextField1ActionPerformed(evt);
			}
		});

		javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
		jPanel3.setLayout(jPanel3Layout);
		jPanel3Layout.setHorizontalGroup(
				jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
						.addContainerGap()
						.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
								.addComponent(jTextField1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 190, Short.MAX_VALUE)
								.addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 190, Short.MAX_VALUE))
								.addContainerGap())
		);
		jPanel3Layout.setVerticalGroup(
				jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(jPanel3Layout.createSequentialGroup()
						.addContainerGap()
						.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
						.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
						.addContainerGap())
		);

		javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
		jPanel2.setLayout(jPanel2Layout);
		jPanel2Layout.setHorizontalGroup(
				jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGap(0, 0, Short.MAX_VALUE)
		);
		jPanel2Layout.setVerticalGroup(
				jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGap(0, 259, Short.MAX_VALUE)
		);

		jTextArea2.setColumns(20);
		jTextArea2.setRows(5);
		jTextArea2.setText("Advertisements");
		jScrollPane4.setViewportView(jTextArea2);

		jMenu1.setText("Create");
		jMenu1.setSize(1, 1);

		jMenu1.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jMenu1ActionPerformed(evt);
			}
		});
		jMenuBar1.add(jMenu1);

		jMenu2.setText("Share");
		jMenu2.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jMenu2ActionPerformed(evt);
			}
		});
		jMenuBar1.add(jMenu2);

		jMenu3.setText("Save");
		jMenu3.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jMenu3ActionPerformed(evt);
			}
		});
		jMenuBar1.add(jMenu3);

		jMenu4.setText("Edit");
		jMenu4.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jMenu4ActionPerformed(evt);
			}
		});
		jMenuBar1.add(jMenu4);

		jMenu5.setText("Invite");
		jMenu5.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jMenu5ActionPerformed(evt);
			}
		});
		jMenuBar1.add(jMenu5);

		jMenu6.setText("Logout");
		jMenu6.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jMenu6ActionPerformed(evt);
			}
		});
		jMenuBar1.add(jMenu6);


		setJMenuBar(jMenuBar1);

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(
				layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
						.addContainerGap()
						.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 465, javax.swing.GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
								.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
								.addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 210, Short.MAX_VALUE))
								.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
								.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
								.addContainerGap())
		);
		layout.setVerticalGroup(
				layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(layout.createSequentialGroup()
						.addContainerGap()
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
								.addGroup(layout.createSequentialGroup()
										.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
												.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
												.addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 259, Short.MAX_VALUE))
												.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
												.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
												.addComponent(jTabbedPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 499, Short.MAX_VALUE)
												.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 403, javax.swing.GroupLayout.PREFERRED_SIZE)
												.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
												.addGap(27, 27, 27))
		);

		pack();
	}// </editor-fold>//GEN-END:initComponents

	private void jMenu1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu1ActionPerformed
		System.out.println ("called");
	}//GEN-LAST:event_jMenu1ActionPerformed

	private void jMenu2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu2ActionPerformed
		// TODO add your handling code here:
	}//GEN-LAST:event_jMenu2ActionPerformed

	private void jMenu3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu3ActionPerformed
		// TODO add your handling code here:
	}//GEN-LAST:event_jMenu3ActionPerformed

	private void jMenu4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu4ActionPerformed
		// TODO add your handling code here:
	}//GEN-LAST:event_jMenu4ActionPerformed



	@SuppressWarnings("deprecation")
	private void onlineUsersMouseClicked(java.awt.event.MouseEvent evt) {

		if(t.isAlive()){
			//pop up 
			if(onlineUsers.getSelectedValue()!=null)
			{
				Object[] options = { "YES", "NO" };
				int choice = JOptionPane.showOptionDialog(null,
						"Do you want to start a new chat?",
						" ",
						JOptionPane.YES_NO_OPTION,
						JOptionPane.QUESTION_MESSAGE,
						null,
						options,
						options[0]);
				
				if (choice == JOptionPane.NO_OPTION)
				{
					System.out.println("No new chat ");
					return;
				}
				
				if (choice == JOptionPane.YES_OPTION){
					t.stop();
					jTextArea1.setText("");
					System.out.println("New chat wanted");
					//tecBoxServer.endChat();
				}
			}
		}
	
		else{
			if(onlineUsers.getSelectedValue()!=null)
			{
				Object[] options = { "TEXT", "VOICE" };
				int choice = JOptionPane.showOptionDialog(null,
						"Text or  Voice choice invite",
						" ",
						JOptionPane.YES_NO_OPTION,
						JOptionPane.QUESTION_MESSAGE,
						null,
						options,
						options[0]);

				// interpret the user's choice
				if (choice == JOptionPane.YES_OPTION)
				{
					destForTextChat=(String)onlineUsers.getSelectedValue();
					System.out.println("Text chat yes option" + destForTextChat);

					//Chat doc................................................................................
					try {

						for(UserInfo u : users){
							if(u.getUsername().equals(destForTextChat)){
								destUser=u;
								break;
							}
						}
						System.out.println("destUser   :" + destUser.getUsername());
						tecBoxServer.regForChat(me,destUser);

					} catch (RemoteException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					//Chat doc ended..........................................................................................
				}

				if(choice == JOptionPane.NO_OPTION){
					destForVoiceChat=(String)onlineUsers.getSelectedValue();
					System.out.println("Voice chat no option" + destForVoiceChat);
					//Voice chat
				}
			}
		}
	}

	//Added for client req for chat 
	public void StartTxtChat(UserInfo dest){

		destForTextChat=dest.getUsername();

		DocPermissions docPerm1=new DocPermissions(1000,me.getUserid(), "readonly");
		DocPermissions docPerm2=new DocPermissions(1000,dest.getUserid(), "readonly");

		DocPermissions[] permArray={docPerm1,docPerm2};
		UserInfo[] usersText = {dest};

		chatDoc=new Document(1000,me,usersText,permArray,"dummy_doc");
		userDocs.add(chatDoc);

		txtchat.setDocPasser(chatDoc);
		t=new Thread(txtchat);
		t.start();

		System.out.println("After creation of chat doc ..................");



	}


	private void jMenu5ActionPerformed(java.awt.event.ActionEvent evt) {


	}

	@SuppressWarnings("deprecation")
	private void jMenu6ActionPerformed(java.awt.event.ActionEvent evt) {
		try {
			System.out.println ("logout request");   
			tecBoxServer.logout(me);
			System.exit(1);

			//Kill the thread wen user logs out
			t.stop();


		} catch (RemoteException e) {

			e.printStackTrace();
		}
	}

	private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {

		System.out.println("In jTextFieldActionP ");
		String getText = jTextField1.getText();
		String tokens[] = me.getUsername().split("@");
		jTextArea1.append("\n" + tokens[0] + ":" + getText);
		jTextField1.setText("");

		txtchat.sendChatMsg(destForTextChat,getText);
	}//GEN-LAST:event_jTextField1ActionPerformed

	/**
	 * @param args the command line arguments
	 */
	public static void main(String args[]) {
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				new LoggedIn().setVisible(true);
			}
		});
	}

	// Variables declaration - do not modify//GEN-BEGIN:variables
	private javax.swing.JList docList;
	private javax.swing.JLabel jLabel1;
	private javax.swing.JLabel jLabel2;
	private javax.swing.JMenuItem jMenu1;
	private javax.swing.JMenuItem jMenu2;
	private javax.swing.JMenuItem jMenu3;
	private javax.swing.JMenuItem jMenu4;
	private javax.swing.JMenuItem jMenu5;
	private javax.swing.JMenuItem jMenu6;
	private javax.swing.JMenuBar jMenuBar1;
	private javax.swing.JPanel jPanel1;
	private javax.swing.JPanel jPanel2;
	private javax.swing.JPanel jPanel3;
	private javax.swing.JScrollPane jScrollPane1;
	private javax.swing.JScrollPane jScrollPane2;
	private javax.swing.JScrollPane jScrollPane3;
	private javax.swing.JScrollPane jScrollPane4;
	private javax.swing.JSeparator jSeparator1;
	private javax.swing.JTabbedPane jTabbedPane1;
	public javax.swing.JTextArea jTextArea1;
	private javax.swing.JTextArea jTextArea2;
	private javax.swing.JTextField jTextField1;
	private javax.swing.JList onlineUsers;
	// End of variables declaration//GEN-END:variables

}
